package com.xsq.netty;

import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;

import androidx.annotation.Nullable;

import com.xsq.netty.utils.LogUtils;

public class NettyService extends Service {

    private INettyClient iNettyClient;
    private final INettyService.Stub iNettyService = new INettyService.Stub() {
        @Override
        public boolean isConnected() throws RemoteException {
            return iNettyClient.isConnected();
        }

        @Override
        public boolean hasConnection() throws RemoteException {
            return iNettyClient.haveConnection();
        }

        @Override
        public void connect() throws RemoteException {
            iNettyClient.connect();
        }

        @Override
        public void sendMessage(String msg) throws RemoteException {
            iNettyClient.sendMessage(msg);
        }

        @Override
        public void setHeartbeatMsg(String msg) throws RemoteException {
            iNettyClient.setHeartbeatMsg(msg);
        }

        @Override
        public void sendData(Intent intent) throws RemoteException {
            if (intent != null) {
                Bundle bundle = intent.getBundleExtra("extra_bundle");
                if (bundle != null) {
                    int invokingCode = bundle.getInt("invoking_code");
                    switch (invokingCode) {
                        case 1000:
                            IBinder iBinder = bundle.getBinder("binder_netty_listener");
                            if (iBinder != null) {
                                NettyHelper.getInstance().addNettyListener(iBinder);
                                LogUtils.i(NettyHelper.TAG, "add netty listener: " + iBinder);
                            }
                            break;
                        case -1000:
                            IBinder removeIBinder = bundle.getBinder("binder_netty_listener");
                            if (removeIBinder != null) {
                                NettyHelper.getInstance().removeNettyListener(removeIBinder);
                                LogUtils.i(NettyHelper.TAG, "remove a netty listener: " + removeIBinder);
                            }
                            break;
                    }
                }
            }
        }
    };

    @Override
    public void onCreate() {
        super.onCreate();
        iNettyClient = NettyClient.getInstance();
        LogUtils.i("NettyService", "onCreate-->packageName: "+getPackageName());
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return iNettyService;
    }
}